import { getFetch, postFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import React, { useEffect, useRef, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import { io } from 'socket.io-client';
import {
  Form,
  Divider,
  Modal,
  Skeleton,
  Button,
  Input,
  Select,
  message,
  Upload,
} from 'antd';
import { connect, history } from 'umi';
import { PlusOutlined, PhoneFilled, SendOutlined } from '@ant-design/icons';
import './index.less';
import BackIcon from '@/components/BackIcon';
import ChartItem from './ChartItem';
import { OfficePreview, RemoteTxtFilePreview } from './office';
import Recorder from '@/components/Recorder/index';
import ImagePicker from '@/components/ImagePicker/index';
import IconFont from '@/components/IconFont';

const socket = io(REACT_APP_URL, {
  query: { customerId: localStorage.getItem('ID') },
});

// const typeconfig = {
//   text: "文字",
//   picture: "图片",
//   audio: "语音",
//   file:  "文件"
// }
let n = 0;

function Chat({ companies, userinfo }) {
  const [pageIndex, setPageIndex] = useState(1);
  const [data, setData] = useState([]);
  const [val, onChange] = useState();

  const { loading, ...other } = useRequest(
    async () => {
      let res = await getFetch({
        url: '/wbn-api/wechat/customers/chat_message',
        params: {
          company_id: companies?.id,
          pageIndex,
        },
      });
      return res?.data;
    },
    {
      refreshDeps: [pageIndex],
      debounceWait: 400,
      onSuccess: (res) => {
        const thisresult = res?.list ?? [];
        setData([...data, ...thisresult]);
        if (n === 0) {
          loadMoreData();
          n = 1;
        }
      },
    },
  );

  const loadMoreData = () => {
    setPageIndex((s) => s + 1);
  };

  useEffect(() => {
    socket.connect();
    socket.on(`chat-customer-${userinfo?.id}`, (params) => {
      let res = JSON.parse(params);
      setData((s) => [res, ...s]);
    });

    socket.on('chat-user', (params) => {
      let res = JSON.parse(params);
      setData((s) => [res, ...s]);
    });
  }, []);

  const [modals, setModals] = useState({
    open: false,
    onCancel: (e) => {
      setModals((s) => ({ ...s, open: false }));
    },
  });

  const [form] = Form.useForm();

  const [isopen, setIsopen] = useState(false);

  const [modal, setModal] = useState({
    open: false,
    onCancel: () => {
      setModal((s) => ({
        ...s,
        open: false,
      }));
    },
  });

  return (
    <div
      id="scrollableDiv"
      style={{
        height: 'calc(100vh - 136px)',
        overflow: 'auto',
        width: '100%',
        display: 'flex',
        flexDirection: 'column-reverse',
        marginTop: 65,
        paddingBottom: isopen ? 65 : 0,
      }}
    >
      <Modal
        {...modals}
        onOk={() => {
          form.submit();
        }}
        okText={'提交'}
        {...(modals.title === '电话沟通' ? { footer: false } : {})}
      >
        {modals.title === '电话沟通' ? (
          <div>
            <p className="title">客服电话</p>
            <a
              href="tel:13338072099"
              style={{ marginBottom: 18, display: 'block' }}
            >
              13338072099
            </a>
            <p className="title">开票电话</p>
            <a href="tel:18115813605">18115813605</a>
          </div>
        ) : (
          <Form
            form={form}
            layout={'vertical'}
            onFinish={(val) => {
              postFetch({
                url: '/wbn-api/wechat/customers/complaint',
                params: {
                  ...val,
                  customer_id: userinfo?.id,
                  company_id: companies.id,
                },
              }).then((res) => {
                if (res.code === 0) {
                  setModals((s) => ({
                    ...s,
                    open: false,
                  }));
                  setTimeout(() => {
                    message.success('投诉成功，投诉进度见个人中心-投诉列表');
                    form.resetFields();
                  }, 1000);
                }
              });
            }}
          >
            <Form.Item
              name={'complaint_setting_id'}
              label="选择投诉类型"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Select options={modals?.options} />
            </Form.Item>
            <Form.Item
              name={'customer_remark'}
              label="备注"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input.TextArea rows={8} maxLength={800} showCount />
            </Form.Item>
          </Form>
        )}
      </Modal>

      <Modal
        {...modal}
        width={'calc(100vw - 40px)'}
        footer={false}
        style={{ top: 20 }}
        destroyOnClose={true}
      >
        {modal?.type === 'txt' ? (
          <div className="centerl">
            <RemoteTxtFilePreview url={modal.url} />
          </div>
        ) : modal?.type === 'mp3' ? (
          <div className="center">
            <audio src={modal?.url} controls />
          </div>
        ) : modal?.type === 'mp4' ? (
          <video
            src={modal?.url}
            controls
            style={{ width: '100%', height: 'calc(100vh - 110px)' }}
          />
        ) : (
          <OfficePreview
            url={modal?.url}
            type={modal?.type}
            name={modal?.title}
          />
        )}
      </Modal>

      <div className="adds center">
        <div
          style={{ fontSize: 16, width: '80%', textAlign: 'center' }}
          className="oneline"
        >
          {companies?.name}
        </div>
        <Button
          style={{ position: 'absolute', right: 12, top: 18, zIndex: 999 }}
          onClick={async () => {
            let res = await getFetch({
              url: '/wbn-api/wechat/customers/complaint_setting',
              params: {},
            });
            setModals((s) => ({
              ...s,
              open: true,
              title: '填写投诉信息',
              options: res?.data?.dataList?.map((it) => ({
                label: it.name,
                value: it.id,
              })),
            }));
          }}
        >
          投诉
        </Button>
      </div>
      <BackIcon></BackIcon>
      <InfiniteScroll
        dataLength={data.length}
        next={loadMoreData}
        hasMore={other?.data?.hasnextpage}
        style={{ display: 'flex', flexDirection: 'column-reverse' }}
        inverse={true}
        loader={
          <Skeleton
            avatar
            paragraph={{
              rows: 1,
            }}
            active
          />
        }
        endMessage={<Divider plain>最顶部</Divider>}
        scrollableTarget="scrollableDiv"
      >
        {data?.map((it, i) => {
          return (
            <ChartItem
              {...it}
              key={it?.id}
              setModal={setModal}
              companies={companies}
            />
          );
        })}
      </InfiniteScroll>

      <div className="footer">
        <div className="center" style={{ gap: 12 }}>
          <Button
            size="large"
            type="primary"
            style={{ border: 'none', borderRadius: 6 }}
            icon={<PhoneFilled rotate={90} />}
            onClick={() => {
              setModals((s) => ({
                ...s,
                open: true,
                title: '电话沟通',
              }));
            }}
          />
          <Input
            size="large"
            bordered={false}
            placeholder="发送文本"
            value={val}
            onChange={(e) => {
              onChange(e.target.value);
            }}
            style={{
              backgroundColor: '#fff',
              height: 40,
              flex: 1,
              borderRadius: 6,
            }}
            onPressEnter={(e) => {
              socket.emit(
                'customer-message',
                JSON.stringify({
                  company_id: companies?.id,
                  message_type: 'text',
                  message_content: e.target.value,
                }),
                (res) => {
                  onChange();
                },
              );
            }}
          />
          <Button
            size="large"
            type="text"
            style={{ backgroundColor: '#fff', border: 'none', borderRadius: 6 }}
            icon={<PlusOutlined rotate={isopen ? 45 : 0} />}
            onClick={() => {
              setIsopen(!isopen);
            }}
          />
          <Button
            size="large"
            type="primary"
            style={{ border: 'none', borderRadius: 6 }}
            icon={<SendOutlined />}
            onClick={() => {
              if (!val) {
                message.info('请输入内容');
                return;
              }
              socket.emit(
                'customer-message',
                JSON.stringify({
                  company_id: companies?.id,
                  message_type: 'text',
                  message_content: val,
                }),
                (res) => {
                  onChange();
                },
              );
            }}
          />
        </div>
        <div
          className="actionbar"
          style={{ height: isopen ? 'auto' : 0, overflow: 'hidden' }}
        >
          <div style={{ width: '100%', height: 12 }} />
          <div className="centerl" style={{ gap: 12 }}>
            <ImagePicker socket={socket} companies={companies}></ImagePicker>

            {/* <div
              key="pic"
              name="file"
              listType="picture-card"
              style={{
                height: 'auto',
                width: 'auto',
                border: 'none',
                padding: 12,
                borderRadius: 8,
                backgroundColor: '#fff',
              }}
              showUploadList={false}
              action={'/wbn-api/file'}
              beforeUpload={(file) => {
                const isJpgOrPng =
                  file.type === 'image/jpeg' || file.type === 'image/png';
                if (!isJpgOrPng) {
                  message.error('仅支持 JPG/PNG 文件!');
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  message.error('图片需要小于 2MB!');
                }
                return isJpgOrPng && isLt2M;
              }}
              onChange={(info) => {
                if (info.file.status === 'uploading') {
                  return;
                }
                if (info.file.status === 'done') {
                  // Get this url from response in real world.
                  const url = info?.file?.response?.data?.origin_url;
                  socket.emit(
                    'customer-message',
                    JSON.stringify({
                      company_id: companies?.id,
                      message_type: 'picture',
                      message_content: url,
                    }),
                  );
                }
              }}
              onClick={()=>{
                wx.chooseImage({
                  count: 1, // 默认9
                  sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                  sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                  success: function (res) {
                  var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                  }
                });
              }}
            >
              <img
                style={{ width: 32, height: 32 }}
                src={require('@/assets/image.svg')}
                alt=""
              />
            </div> */}
            <Upload
              key="pic"
              name="file"
              listType="picture-card"
              style={{
                height: 'auto',
                width: 'auto',
                border: 'none',
                padding: 12,
                borderRadius: 8,
                backgroundColor: '#fff',
              }}
              showUploadList={false}
              action={'/wbn-api/file'}
              beforeUpload={(file) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  message.error('图片需要小于 2MB!');
                }
                return isLt2M;
              }}
              onChange={(info) => {
                if (info.file.status === 'uploading') {
                  return;
                }
                if (info.file.status === 'done') {
                  // Get this url from response in real world.
                  const url = info?.file?.response?.data?.origin_url;
                  socket.emit(
                    'customer-message',
                    JSON.stringify({
                      company_id: companies?.id,
                      message_type: 'file',
                      message_content: url,
                    }),
                  );
                }
              }}
            >
              <img
                style={{ width: 32, height: 32 }}
                src={require('@/assets/file.svg')}
                alt=""
              />
            </Upload>
            <Recorder socket={socket} companies={companies}></Recorder>

            <div
              className="center cad"
              onClick={() => {
                history.push('/invoice');
              }}
            >
              <IconFont
                type="icon-Invoice_fill"
                style={{ fontSize: 30, color: '#44cef6' }}
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default connect(({ global, loading }) => ({
  companies: global.companies,
  userinfo: global.userinfo,
  loading,
}))(Chat);
